package net.edu_soft.ec.common.interceptor;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;


import net.edu_soft.ec.asset.pojo.SysLog;
import net.edu_soft.ec.asset.pojo.UserInfo;
import net.edu_soft.ec.asset.service.SysLogService;
import net.edu_soft.ec.common.annotation.SysLogInfo;
import net.edu_soft.ec.common.util.IpAdrressUtil;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;

/**
 * @ClassName: SysLogAspect
 * @Description: 系统日志：切面处理类
 * @author PUING
 * @Date 2020/6/17 18:30
 */
@Aspect
@Component
public class SysLogAspect {

	@Autowired
    private SysLogService sysLogService;

    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation(net.edu_soft.ec.common.annotation.SysLogInfo)")
    public void logPoinCut() {
    }

  //切面 配置通知
    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        System.out.println("切面。。。。。");
        //保存日志
        SysLog sysLog = new SysLog();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //获取操作
        SysLogInfo myLog = method.getAnnotation(SysLogInfo.class);
        if (myLog != null) {
            String value = myLog.value();
            sysLog.setOperation(value);//保存获取的操作
        }

        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName = method.getName();
        sysLog.setMethod(className + "." + methodName);

        //请求的参数
        Object[] args = joinPoint.getArgs();
        System.out.println("object参数："+args.toString());
        //将参数所在的数组转换成json
        String params = JSON.toJSONString(args);
        System.out.println("json参数："+params);
        sysLog.setParams(params);

        sysLog.setCreateDate(new Date());
        //获取用户名
        //sysLog.setUserName(((UserInfo) SecurityUtils.getSubject().getPrincipal()).getUsername());
        sysLog.setUserName("测试用户");
        //获取用户ip地址
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        sysLog.setIpAddress(IpAdrressUtil.getIpAdrress(request));


        //调用service保存SysLog实体类到数据库
        System.out.println("保存数据--------");
        sysLogService.save(sysLog);
    }
       
}
